<script setup>
import {ref } from 'vue'


const infoList = ref([
  {
    id: 12121,
    title: '陈平安',
    size: 4,
    floor: 1,
    description: '骊珠洞天泥瓶巷'
  },
  {
    id: 21212,
    title: '张三峰',
    size: 3,
    floor: 2,
    description: '北俱芦洲趴地峰'
  },
]);
const infoShow = ref(false);
const infoForm = ref({})
const remove = (id) => {
  infoList.value = infoList.value.filter(item => item.id !== id)
}

const openInfo = () => {
  infoForm.value = {}
  infoShow.value = true
}
const save = () => {
  //1. 检测数据
  const info = {...infoForm.value}
  if (!info.title?.trim()){
    return;
  }
  if (info.size<=0 ){
    return;
  }
  if (info.floor<=-5 ){
    return;
  }
  //2.将数据添加到infoList中
  //如果有id，就是修改
  if (info.id){
    // 找到这个id对应的数据在数组中的位置
    const index = infoList.value.findIndex(item => item.id === info.id)
    infoList.value[index] = info;
  }else{
    info.id = new Date().getTime();
    infoList.value.push(info)
  }

  //3.关闭弹窗
  infoShow.value = false
}
const openEdit = (id) => {
  const info = infoList.value.find(item => item.id === id);
  infoForm.value = {...info}
  infoShow.value = true;
}
</script>

<template>
  <div>
    <el-button type="primary" @click="openInfo" style="margin-bottom: .5rem">添加</el-button>
  </div>

  <el-table :data="infoList" border stripe>
    <el-table-column prop="id" label="编号" width="180"/>
    <el-table-column prop="title" label="名称" width="180"/>
    <el-table-column prop="size" label="床铺数" width="180"/>
    <el-table-column prop="floor" label="楼层" width="180"/>
    <el-table-column prop="description" label="描述"/>
    <el-table-column label="操作" width="180">
      <template #default="props">
        <el-button type="primary" size="small" @click="openEdit(props.row.id)">编辑</el-button>
        <el-button type="danger" size="small" @click="remove(props.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>


  <div>
    <el-dialog v-model="infoShow" title="详情" width="500">
      <el-form :model="infoForm">
        <el-form-item label="名称" :label-width="60">
          <el-input v-model="infoForm.title"  />
        </el-form-item>
        <el-form-item label="床铺数" :label-width="60">
          <el-input v-model="infoForm.size" type="number" min="1"/>
        </el-form-item>
        <el-form-item label="楼层" :label-width="60">
          <el-input v-model="infoForm.floor" type="number" min="-4"/>
        </el-form-item>
        <el-form-item label="描述" :label-width="60">
          <el-input v-model="infoForm.description"  />
        </el-form-item>
      </el-form>
      <template #footer>
        <div >
          <el-button @click="infoShow = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<style scoped>

</style>